<template>
  <div :bordered="false">
    <div class="table-operations">
      <a-button type="primary" @click="showAddModal">新增</a-button>
    </div>
    <a-table
      class="width:100%;"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <span slot="certificateDate" slot-scope="text, record" v-if="record.certificateDate">
        {{ new Date(record.certificateDate).toLocaleString() }}
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a @click="handleDelete(record.id)">删除</a>
      </span>
      <span slot="qualPath" slot-scope="text, record">
        <img v-for="v in getImgList(text)" width="50" :src="imgBase + '/' + v" />
      </span>
    </a-table>

    <a-modal v-model="visible" title="证书信息" @ok="handleOk" @cancel="handleCancel" :confirm-loading="confirmLoading">
      <a-form :form="form" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-item label="证书名称">
          <a-input
            v-decorator="['certificateName', { rules: [{ required: true, message: '请输入证书名称' }] }]"
            placeholder="请输入证书名称"
          />
        </a-form-item>
        <a-form-item label="奖项名称">
          <a-input
            v-decorator="['jiangName', { rules: [{ required: true, message: '请输入奖项名称' }] }]"
            placeholder="请输入奖项名称"
          />
        </a-form-item>
        <a-form-item label="证书类别">
          <a-select v-decorator="['certificateType', { rules: [{ required: true, message: '请选择证书类别！' }] }]">
            <a-select-option value="企业证书">企业证书</a-select-option>
            <a-select-option value="个人证书">个人证书</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="获奖时间">
          <a-date-picker
            v-decorator="['certificateDate', { rules: [{ required: true, message: '请选择获奖时间' }] }]"
          />
        </a-form-item>
        <a-form-item label="颁奖部门">
          <a-input
            v-decorator="['certificateDept', { rules: [{ required: true, message: '请输入颁奖部门' }] }]"
            placeholder="请输入颁奖部门"
          />
        </a-form-item>

        <a-form-item label="证书图片">
          <j-upload v-decorator="['certificatePath', { rules: [{ required: true, message: '请上传' }] }]"></j-upload>
        </a-form-item>

        <a-form-item label="说明">
          <a-textarea
            v-decorator="['remark', { rules: [{ required: false, message: '请输入说明' }] }]"
            placeholder="请输入说明"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { axios } from '@/utils/request'
import { mapGetters } from 'vuex'
import { Modal } from 'ant-design-vue'
import { tableMixin, tableImgMixin } from './mixin'
export default {
  name: 'step6',
  components: {},
  mixins: [tableMixin, tableImgMixin],
  data() {
    return {
      form: this.$form.createForm(this),
      visible: false,
      confirmLoading: false,
      uploadedFiles: {},
      columns: [
        { title: '证书名称', dataIndex: 'certificateName', key: 'certificateName' },
        { title: '奖项名称', dataIndex: 'jiangName', key: 'jiangName' },
        {
          title: '获奖时间',
          dataIndex: 'certificateDate',
          key: 'certificateDate',
          scopedSlots: { customRender: 'certificateDate' },
        },
        { title: '颁奖部门', dataIndex: 'certificateDept', key: 'certificateDept' },

        {
          title: '证书图片',
          dataIndex: 'certificatePath',
          key: 'certificatePath',
          scopedSlots: { customRender: 'qualPath' },
        },
        { title: '证书类别', dataIndex: 'certificateType', key: 'certificateType' },

        { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } },
      ],
      dataSource: [],

      currentRecord: null,
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  props: {
    canFix: {
      type: Boolean,
    },
    // 基本类型检查 (`null` 和 `undefined` 会通过任何类型验证)
    legalCode: String,
  },
  methods: {
    async getData() {
      try {
        const response = await axios.get('/register/subjectLegalCertificate/list', {
          params: { legalCode: this.legalCode, pageSize: this.pagination.pageSize, pageNo: this.pagination.current },
        })
        const data = response.result.records
        this.dataSource = data
        this.pagination.total = response.result.total
      } catch (error) {
        console.error('Failed to fetch certificates:', error)
      }
    },
    showAddModal() {
      this.visible = true
      this.currentRecord = null
      this.form.resetFields()
    },
    handleEdit(record) {
      this.visible = true
      this.currentRecord = { ...record }
      this.$nextTick(() => {
        this.form.setFieldsValue(this.currentRecord)
      })
    },
    handleDelete(id) {
      Modal.confirm({
        title: '确认删除',
        content: '确定要删除这条记录吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          try {
            await axios.delete(`/register/subjectLegalCertificate/delete?id=${id}`)
            this.getData()
            this.$message.success('删除成功！')
          } catch (error) {
            console.error('Failed to delete certificate:', error)
            this.$message.error('删除失败，请重试！')
          }
        },
      })
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          const method = this.currentRecord ? 'put' : 'post'
          const url = this.currentRecord
            ? `/register/subjectLegalCertificate/edit`
            : '/register/subjectLegalCertificate/add'
          const payload = { ...values, id: this.currentRecord?.id, legalCode: this.legalCode }

          axios[method](url, payload)
            .then(() => {
              this.visible = false
              this.confirmLoading = false
              this.getData()
              this.$message.success(`${method === 'post' ? '添加' : '更新'}成功！`)
            })
            .catch(error => {
              console.error(`Failed to ${method} certificate:`, error)
              this.confirmLoading = false
              this.$message.error(`${method === 'post' ? '添加' : '更新'}失败，请重试！`)
            })
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.form.resetFields()
    },

    dummyRequest({ file, onSuccess }) {
      setTimeout(() => {
        onSuccess('ok')
      }, 0)
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = {
        ...this.pagination,
        current: pagination.current,
        pageSize: pagination.pageSize,
      }
      this.getData()
    },
  },
  created() {
    this.getData()
  },
}
</script>

<style scoped>
.table-operations {
  margin-bottom: 16px;
}
</style>
